<template>
  <!-- 顶部导航菜单 -->
  <ExamMenu />

  <div class="practice-container">
    <!-- 左侧答题卡 -->
    <div class="left-panel">
      <!-- 用户信息 -->
      <div class="user-info">
        <el-avatar :size="50" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
        <div class="user-details">
          <div class="username">{{ userInfo.name }}</div>
          <div class="last-active">最后活动：{{ formattedTime }}</div>
        </div>
      </div>

      <!-- 答题卡 -->
      <div class="answer-sheet">
        <h3>答题卡</h3>
        <div class="pagination-header">
          <span>共 {{ questions.length }} 题</span>
          <div class="page-size-selector">
            每页显示：
            <el-select v-model="pageSize" size="mini" style="width: 80px">
              <el-option v-for="size in pageSizes" :key="size" :value="size" />
            </el-select>
          </div>
        </div>

        <div class="question-numbers">
          <el-button v-for="(question, localIndex) in currentPageQuestions" :key="question.quId"
            :type="getButtonType(question)" @click="goToQuestion(getGlobalIndex(localIndex))" :class="{
              'current-question': currentQuestionIndex === getGlobalIndex(localIndex),
              'current-page-highlight': currentPage === Math.floor(getGlobalIndex(localIndex) / pageSize) + 1
            }" circle>
            <el-tooltip :content="question.answerTime ? formatQuestionTime(question.answerTime) : '未作答'" placement="top">
              {{ getGlobalIndex(localIndex) + 1 }}
            </el-tooltip>

          </el-button>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-controls">
          <el-button @click="currentPage--" :disabled="currentPage === 1" size="small">
            &lt; 上一页
          </el-button>
          <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          <el-button @click="currentPage++" :disabled="currentPage === totalPages" size="small">
            下一页 &gt;
          </el-button>
        </div>
      </div>
      <!--答题卡-->
    </div>

    <!-- 右侧题目区域 -->
    <div class="right-panel">
      <!-- 题库信息 -->
      <div class="bank-info">
        <el-tag type="success" effect="dark" size="large">
          当前题库：{{ questionBankName }}
        </el-tag>
      </div>

      <div class="question-area">
        <!-- 进度条 -->
        <el-progress :percentage="progressPercentage" :status="progressStatus" :show-text="false" />

        <!-- 题目内容 -->
        <div class="question-content">
          <h2>第 {{ currentQuestionIndex + 1 }} 题</h2>
          <span class="question-type-tag" :data-type="questionTypeText">（{{ questionTypeText }}）</span>
          <p class="question-text">{{ currentQuestion.content }}</p>

          <!--简答题、编程题 start-->

          <!-- 简答/编程题输入区域 -->
          <div v-if="[4, 5].includes(currentQuestion.quType)" class="code-editor">
            <el-input v-if="currentQuestion.quType === 4" v-model="currentQuestion.userAnswer" type="textarea" :rows="8"
              placeholder="请输入你的答案" />
            <div v-else class="monaco-editor-container">
              <!-- 这里可以接入 Monaco Editor -->
              <div ref="editorContainer" class="code-editor"></div>
            </div>
          </div>
          <!--简答题、编程题 end-->

          <!-- 单选题、多选题、判断题选项列表 start-->
          <div class="options-list" v-else>
            <el-button v-for="(option, index) in currentQuestion.options" :key="option.id" class="option-button"
              :class="getOptionClass(index)" @click="selectOption(index)" :disabled="showAnswer">
              {{ option.content }}
            </el-button>
          </div>

          <!---单选题、多选题、判断题选项end-->

        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="drawerVisible = true">
            <el-icon>
              <View />
            </el-icon> 查看解析
          </el-button>
           <!-- 多选题提交按钮 -->
           <el-button 
            v-if="currentQuestion.quType === 2" 
            type="success" 
            @click="handleMultipleSubmit"
            :disabled="!isMultiSelected"
          >
            <el-icon><Upload /></el-icon> 提交多选题答案
          </el-button>
          <!-- 新增提交按钮 -->
          <el-button v-if="[4, 5].includes(currentQuestion.quType)" type="success" @click="handleSubmit"
            :disabled="!currentQuestion.userAnswer">
            <el-icon>
              <Upload />
            </el-icon> 提交答案
          </el-button>
        </div>

        <!-- 导航按钮 -->
        <div class="navigation-buttons">
          <el-button type="primary" @click="prevQuestion" :disabled="currentQuestionIndex === 0">
            上一题
          </el-button>
          <el-button type="primary" @click="nextQuestion" :disabled="currentQuestionIndex === questions.length - 1">
            下一题
          </el-button>
        </div>

        <!-- 统计信息 -->
        <div class="stats">
          <span>正确率：{{ correctCount }}/{{ answeredCount }}</span>
          <span>进度：{{ currentQuestionIndex + 1 }}/{{ questions.length }}</span>
        </div>
      </div>
    </div>

    <!-- 答案解析抽屉 -->
    <el-drawer v-model="drawerVisible" title="题目解析" size="40%">
      <div class="analysis-content">
        <h3>正确答案：</h3>
        <div class="correct-answers">
          <el-tag v-for="option in correctOptions" :key="option.id" type="success">
            {{ option.content }}
          </el-tag>
        </div>
        <h3>解析：</h3>
        <div class="analysis-text">
          {{ currentQuestion.analysis || '暂无解析' }}
        </div>
      </div>
    </el-drawer>
  </div>

  <!-- 底部 -->
  <ExamFooter />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Star, View } from '@element-plus/icons-vue'
import ExamMenu from '@/components/comm/ExamMenu.vue'
import ExamFooter from '@/components/comm/ExamFooter.vue'
import { getQuestionListApi, getQuestionDetailApi, fillAnswerApi } from '@/api/exercise'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import * as monaco from 'monaco-editor'
import 'dayjs/locale/zh-cn'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')
interface Question {
  quId: number
  quType: number
  content: string
  analysis?: string
  bankId: number
  options: QuestionOption[]
  answerTime?: number
  userAnswer?: number
  isCorrect?: boolean
  tempAnswers?: number[]
}

interface QuestionOption {
  id: number
  content: string
  isRight: number
}


// 用户信息
const userStore = useUserStore()
const userInfo = ref({
  name: userStore.name,
  lastActive: Date.now()
})

// 路由参数
const route = useRoute()
const bankId = computed(() => Number(route.query.bankId))

// 题库数据
const questionBankName = ref('')
const questions = ref<Question[]>([])
const currentQuestion = ref<Question>({} as Question)
const currentQuestionIndex = ref(0)
const selectedIndex = ref<number>()
const showAnswer = ref(false)
const drawerVisible = ref(false)

// 新增题型文本计算属性
const questionTypeText = computed(() => {
  switch (currentQuestion.value.quType) {
    case 1: return '单选题'
    case 2: return '多选题'
    case 3: return '判断题'
    case 4: return '简答题'
    case 5: return '编程题'
    default: return '未知题型'
  }
})

// 新增分页相关代码
const pageSizes = [20, 50, 100]
const pageSize = ref(50)
const currentPage = ref(1)

// 计算属性
const totalPages = computed(() => Math.ceil(questions.value.length / pageSize.value))
const currentPageQuestions = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return questions.value.slice(start, end)
})

// 全局索引计算
const getGlobalIndex = (localIndex: number) => {
  return (currentPage.value - 1) * pageSize.value + localIndex
}

// 监听当前题目变化自动切换页码
watch(currentQuestionIndex, (newIndex) => {
  const targetPage = Math.floor(newIndex / pageSize.value) + 1
  if (targetPage !== currentPage.value) {
    currentPage.value = targetPage
  }
})

// 监听分页大小变化重置页码
watch(pageSize, () => {
  currentPage.value = Math.floor(currentQuestionIndex.value / pageSize.value) + 1
})

// 时间格式化函数
const formatQuestionTime = (timestamp?: number) => {
  if (!timestamp) return ''
  return dayjs(timestamp).fromNow()
}

const formattedTime = computed(() => {
  return dayjs(userInfo.value.lastActive).fromNow()
})

// 获取题库列表
const getQuestionBank = async () => {
  try {
    const { data } = await getQuestionListApi(bankId.value)
    console.log('能否进入到这里')
    questions.value = data.map((q: any) => ({
      quId: q.quId,
      quType: q.quType,
      answerTime: undefined,
      userAnswer: undefined,
      isCorrect: undefined
    }))

    if (questions.value.length > 0) {

      await getQuestionDetail(questions.value[0].quId)
    }
  } catch (error) {
    ElMessage.error('题库加载失败')
  }
}

// 获取题目详情
const getQuestionDetail = async (quId: number) => {
  try {
    const { data } = await getQuestionDetailApi(quId)
    const localQuestion = questions.value.find(q => q.quId === quId)
    currentQuestion.value = {
      ...data,
      options: data.options.map(opt => ({
        ...opt,
        // 保留本地可能存在的正确答案状态
        isRight: localQuestion?.options?.find(o => o.id === opt.id)?.isRight ?? opt.isRight
      })),
      answerTime: localQuestion?.answerTime,
      userAnswer: localQuestion?.userAnswer,
      isCorrect: localQuestion?.isCorrect
    }
    questionBankName.value = data.bankTitle
  } catch (error) {
    ElMessage.error('题目加载失败')
  }
}

// 新增计算属性：是否有多选选中项
const isMultiSelected = computed(() => {
  return currentQuestion.value.tempAnswers?.length > 0
})

// 选择答案
const selectOption = async (index: number) => {
  if (showAnswer.value) return

  selectedIndex.value = index
  

  // 判断当前题目类型
  const isMultiple = currentQuestion.value.quType === 2
  // 多选题
  if (isMultiple) {
    // 当前选项已选择的ID
    const optionId = currentQuestion.value.options[index].id
    console.log('当前选项已选择的ID',optionId)
    const temp = currentQuestion.value.tempAnswers || []
    const idx = temp.indexOf(optionId)
    if (idx > -1) {
      temp.splice(idx, 1) // 取消选择
    } else {
      temp.push(optionId) // 添加选择
    }
    
    currentQuestion.value.tempAnswers = [...temp]
    console.log('当前选项已选择的ID',temp,currentQuestion.value.tempAnswers)
  // 单选题
  }else {
    showAnswer.value = true
    handleSingleAnswer(index)
  }

  
}

// 提交答案，单选题和判断题
const handleSingleAnswer = async (index: number) => {
  try {
    const { data, msg } = await fillAnswerApi({
      bankId: currentQuestion.value.bankId,
      quId: currentQuestion.value.id,
      quType: currentQuestion.value.quType,
      answer: currentQuestion.value.options[index].id
    })

    const isCorrect = data.options[index].isRight === 1
    const currentIdx = currentQuestionIndex.value

    // 更新当前题目状态
    questions.value[currentIdx] = {
      ...questions.value[currentIdx],
      answerTime: Date.now(),
      userAnswer: index,
      isCorrect,
      options: data.options  // 携带正确答案信息
    }

    // 更新显示数据
    currentQuestion.value = {
      ...data,
      answerTime: Date.now(),
      userAnswer: index,
      isCorrect,
      analysis: data.analysis
    }

    ElMessage[isCorrect ? 'success' : 'error'](msg)
  } catch (error) {
    ElMessage.error('提交失败')
  }
}

// 提交答案，多选题
const handleMultipleSubmit = async () => {
  if (!currentQuestion.value.tempAnswers?.length) {
    ElMessage.warning('请至少选择一个答案')
    return
  }
  try {
     // 数组转字符串逗号隔开
     const userAnswer = currentQuestion.value.tempAnswers.join(',')
    const { data, msg } = await fillAnswerApi({
      bankId: currentQuestion.value.bankId,
      quId: currentQuestion.value.id,
      quType: currentQuestion.value.quType,
      answer: userAnswer
    })
    updateQuestionState(data,msg)

  }catch (error) {
    ElMessage.error('提交失败')
  }
}

/**
 * 状态更新
 * @param data 
 * @param msg 
 */
const updateQuestionState = (data: any,msg: string) => {
  const currentIdx = currentQuestionIndex.value
  console.log('当前索引currentIdx：',currentIdx)
  const isCorrect = data.userIsRight === 1

  // 更改左边答题卡当前题目状态
  questions.value[currentIdx] = {
    ...questions.value[currentIdx],
    answerTime: Date.now(),
    userAnswer: currentQuestion.value.tempAnswers,
    isCorrect
  } 


  // 更新抽屉显示数据
  currentQuestion.value = {
    ...data,
    answerTime: Date.now(),
    userAnswer: currentQuestion.value.tempAnswers,
    isCorrect,
    options: data.options  // 携带正确答案信息
  }

  ElMessage[isCorrect? 'success' : 'error'](msg)
}
// 题目导航
const goToQuestion = (index: number) => {
  if (currentQuestionIndex.value === index) return
  currentQuestionIndex.value = index
  resetQuestionState()
  getQuestionDetail(questions.value[index].quId)
}

const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
    resetQuestionState()
    getQuestionDetail(questions.value[currentQuestionIndex.value].quId)
  }
}

const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    resetQuestionState()
    getQuestionDetail(questions.value[currentQuestionIndex.value].quId)
  }
}

// 辅助方法
const resetQuestionState = () => {
  selectedIndex.value = undefined
  showAnswer.value = false
}

// 计算属性 抽屉显示答案
const correctOptions = computed(() => {
  // 1. 安全获取 options，处理未定义的情况
  const options = currentQuestion.value.options || [];
  
  // 2. 过滤出正确答案
  const filtered = options.filter(opt => opt.isRight === 1);
  
  // 3. 打印日志（调试用）
  console.log('correctOptions正确答案计算属性：', filtered);
  
  // 4. 返回结果
  return filtered;
});

console.log('correctOptions正确答案计算属性correctOptions：',correctOptions.value)



const answeredCount = computed(() =>
  questions.value.filter(q => q.userAnswer !== undefined).length
)

const correctCount = computed(() =>
  questions.value.filter(q => q.isCorrect).length
)

const progressPercentage = computed(() =>
  Math.round((answeredCount.value / questions.value.length) * 100)
)

const progressStatus = computed(() =>
  answeredCount.value === questions.value.length ? 'success' : 'primary'
)

const getButtonType = (question: Question) => {
  if (question.userAnswer === undefined) return 'info'
  return question.isCorrect ? 'success' : 'danger'
}

const getOptionClass = (index: number) => {
  const option = currentQuestion.value.options?.[index]
  if (!option) return {}

  const isMultiple = currentQuestion.value.quType === 2
  const isSelected = isMultiple
    ? (currentQuestion.value.tempAnswers || []).includes(option.id)
    : currentQuestion.value.userAnswer === option.id

  const isCorrect = option.isRight === 1
  const showResult = showAnswer.value

  return {
    'selected-option': isSelected && !showResult,
    'correct-option': showResult && isCorrect,
    'wrong-option': showResult && !isCorrect && isSelected
  }
}

const getOptionClass11 = (index: number) => {
  if (!showAnswer.value) return {}

  const isSelected = selectedIndex.value === index
  const isCorrect = currentQuestion.value.options?.[index]?.isRight === 1

  return {
    'correct-option': isCorrect,
    'wrong-option': !isCorrect && isSelected
  }
}

// Monaco 编辑器实例
const editorContainer = ref<HTMLElement>()
let editor: monaco.editor.IStandaloneCodeEditor | null = null

// 初始化编辑器
const initEditor = () => {
  if (!editorContainer.value) return

  // 销毁旧实例
  if (editor) {
    editor.dispose()
  }

  // 创建新实例
  editor = monaco.editor.create(editorContainer.value, {
    value: currentQuestion.value.userAnswer || '',
    language: 'typescript', // 根据题目需求设置语言
    theme: 'vs-dark',
    automaticLayout: true,
    minimap: {
      enabled: false
    },
    scrollBeyondLastLine: false,
    fontSize: 14,
    lineNumbers: 'on',
    roundedSelection: false,
    scrollbar: {
      verticalScrollbarSize: 8,
      horizontalScrollbarSize: 8
    }
  })

  // 监听内容变化
  editor.onDidChangeModelContent(() => {
    currentQuestion.value.userAnswer = editor!.getValue()
  })
}

// 当切换到编程题时初始化编辑器
watch(() => currentQuestion.value.quType, (newVal) => {
  if (newVal === 5) {
    nextTick(() => {
      initEditor()
    })
  }
})

// 当答案变化时同步编辑器
watch(() => currentQuestion.value.userAnswer, (newVal) => {
  if (editor && newVal !== editor.getValue()) {
    editor.setValue(newVal || '')
  }
})

// 简答题和编程题提交答案
const handleSubmit = async () => {
  try {
    if (!currentQuestion.value.userAnswer?.trim()) {
      ElMessage.warning('请输入答案后再提交')
      return
    }


    const { data, msg } = await fillAnswerApi({
      bankId: currentQuestion.value.bankId,
      quId: currentQuestion.value.id,
      quType: currentQuestion.value.quType,
      answer: currentQuestion.value.userAnswer
    })

    // 更新答题卡题目状态
    const currentIdx = currentQuestionIndex.value
    questions.value[currentIdx] = {
      ...questions.value[currentIdx],
      answerTime: Date.now(),
      userAnswer: currentQuestion.value.userAnswer,
      isCorrect: data.userIsRight === 1
    }

    // 更新抽屉答案和解析显示数据
    currentQuestion.value = {
      ...data,
      answerTime: Date.now(),
      analysis: data.analysis
    }

    ElMessage[data.userIsRight === 1 ? 'success' : 'error'](msg)
    drawerVisible.value = true // 自动展开答案解析
  } catch (error) {
    ElMessage.error('提交失败')
  }
}

// 生命周期
onMounted(() => {
  getQuestionBank()
  if (currentQuestion.value.quType === 5) {
    initEditor()
  }
})
onUnmounted(() => {
  if (editor) {
    editor.dispose()
  }
})
</script>

<style lang="scss" scoped>
.practice-container {
  display: flex;
  max-width: 1420px;
  margin: 20px auto;
  gap: 30px;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  // 左侧样式 start

  .left-panel {
    width: 300px;
    background-color: white;
    padding: 20px;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;

    .user-info {
      display: flex;
      align-items: center;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 8px;
      margin-bottom: 20px;

      .user-avatar {
        margin-right: 15px;
      }

      .user-details {
        .username {
          font-weight: 500;
          color: #303133;
        }

        .last-active {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .answer-sheet {
      flex: 1;
      overflow-y: auto;

    
      // 答题卡 分页样式
      // 新增分页样式
      .pagination-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 15px 0;
        font-size: 12px;
        color: #666;

        .page-size-selector {
          display: flex;
          align-items: center;
          gap: 5px;
        }
      }

      .pagination-controls {
        margin-top: 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 15px;

        .page-info {
          font-size: 14px;
          color: #666;
          padding: 0 15px;
        }
      }

      .question-numbers {
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        gap: 10px;
        max-height: 400px;
        overflow-y: auto;
        padding: 5px;

        .current-page-highlight {
          box-shadow: 0 0 0 2px #409eff;
        }


        .current-question {
          // 当前答题卡warning样式
          background-color: #ef9d4b;
        }
      }

      // 调整按钮大小适应分页
      .el-button {
        width: 30px;
        height: 30px;
        display: flex !important;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        position: relative;
        padding: 0;
        line-height: normal;

        // 主数字样式
        >span {
          display: block;
          width: 100%;
          text-align: center;
          line-height: 1;
          padding: 5px 0;
        }

        .answer-time {
          position: absolute;
          bottom: -18px;
          left: 50%;
          transform: translateX(-50%);
          font-size: 10px;
          color: #999;
          white-space: nowrap;
        }
      }

      // 答题卡 分页样式 end


    }
  }

  // 左侧样式 end

  // 右侧题目区域 start
  .right-panel {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;

    // 编辑器样式 start
    .monaco-editor-container {
      height: 400px;
      border: 1px solid #434343;
      border-radius: 4px;
      overflow: hidden;

      .code-editor {
        height: 100%;
      }
    }

    // 调整编辑器主题
    .vs-dark .monaco-editor {
      padding: 10px 0;
    }

    // 编辑器样式 end

    .bank-info {
      margin-bottom: 20px;
    }

    .question-main {
      flex: 1;
      background-color: white;
      border-radius: 8px;
      padding: 30px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    }
  }

  // 右侧题目区域 end

  .question-title {
    color: #303133;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;

    .question-type-tag {
      font-size: 16px;
      color: #409eff;
      font-weight: normal;
      position: relative;
      padding-left: 10px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background-color: #409eff;
        border-radius: 2px;
      }
    }
  }

  /* 根据不同的题型显示不同颜色 */
  .question-type-tag {
    &[data-type="单选题"] {
      color: #67c23a;

      &::before {
        background-color: #67c23a;
      }
    }

    &[data-type="多选题"] {
      color: #e6a23c;

      &::before {
        background-color: #e6a23c;
      }
    }

    &[data-type="判断题"] {
      color: #f56c6c;

      &::before {
        background-color: #f56c6c;
      }
    }

    &[data-type="简答题"] {
      color: #909399;

      &::before {
        background-color: #909399;
      }
    }

    &[data-type="编程题"] {
      color: #a050ff;

      &::before {
        background-color: #a050ff;
      }
    }
  }


  .question-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;

    .progress-bar {
      margin-bottom: 10px;
    }

    .question-content {
      background-color: white;
      padding: 30px;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      flex: 1;

      .question-title {
        color: #303133;
        margin-bottom: 15px;
      }

      .question-text {
        font-size: 16px;
        color: #606266;
        margin-bottom: 25px;
      }

      .options-list {
        display: grid;
        gap: 15px;

        .option-button {
          display: block;
          width: 100%;
          text-align: left;
          transition: all 0.3s;
          margin-left: 12px;

          &.selected-option {
            background-color: #ecf5ff;
            border-color: #b3d8ff;
            color: #409eff;
          }

          &.correct-option {
            background-color: #f0f9eb;
            border-color: #e1f3d8;
            color: #67c23a;
          }

          &.wrong-option {
            background-color: #fef0f0;
            border-color: #fde2e2;
            color: #f56c6c;
            margin-left: 12px;
          }
        }
      }
    }

    .navigation-buttons {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
    }

    .stats {
      display: flex;
      justify-content: space-between;
      color: #909399;
      font-size: 14px;
      padding: 0 20px;
    }
  }
}
</style>